#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem1, sem2;
int num;

void * read(void *arg) {
    sem_wait(&sem1);
    scanf("%d", &num);
    sem_post(&sem2);
    return NULL;
}

void * compute(void *arg) {
    sem_wait(&sem2); 
    int sum = 0;
    for (int i = 1; i <= num; i++)
        sum += i;
    printf("res = %d\n", sum);
    sem_post(&sem1);
    return NULL;
}

int main() {
    sem_init(&sem1, 0, 1);
    sem_init(&sem2, 0, 0);

    pthread_t pid[10];
    for (int i = 0; i < 10; i++) 
        if (i % 2) {
            pthread_create(&pid[i], NULL, read, NULL);
        } else {
            pthread_create(&pid[i], NULL, compute, NULL);
        }   
    
    for (int i = 0; i < 10; i++)
        pthread_join(pid[i], NULL);    

    sem_destroy(&sem1);
    sem_destroy(&sem2);
    
    return 0;
}